//
//  NSString+Category.m
//  iOSCodeProject
//
//  Created by zym on 14-7-18.
//  Copyright (c) 2014年 翔傲信息科技（上海）有限公司. All rights reserved.
//

#import "NSString+Category.h"
#import <CommonCrypto/CommonDigest.h>

int const GGCharacterIsNotADigit = 10;

@implementation NSString (Category)



- (NSString *) stringFromMD5{
    
    if(self == nil || [self length] == 0)
        return nil;
    
    const char *value = [self UTF8String];
    
    unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(value, (CC_LONG)strlen(value), outputBuffer);
    
    NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
        [outputString appendFormat:@"%02x",outputBuffer[count]];
    }
    
    return outputString;
}

+ (NSString*)stringWithFormattedUnsignedInteger:(NSUInteger)integer {
	NSNumber* number = [NSNumber numberWithUnsignedInteger:integer];
	NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
	[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
	NSString* formattedString = [formatter stringFromNumber:number];
	return formattedString;
}

- (BOOL)containsString:(NSString*)string {
	return [self containsString:string options:NSCaseInsensitiveSearch];
}

- (BOOL)containsString:(NSString*)string options:(NSStringCompareOptions)options {
	return [self rangeOfString:string options:options].location == NSNotFound ? NO : YES;
}

#pragma mark -
#pragma mark Long conversions

- (long)longValue {
	return (long)[self longLongValue];
}

- (long long)longLongValue {
	NSScanner* scanner = [NSScanner scannerWithString:self];
	long long valueToGet;
	if([scanner scanLongLong:&valueToGet] == YES) {
		return valueToGet;
	} else {
		return 0;
	}
}

/*
 * Contact info@enormego.com if you're the author and we'll update this comment to reflect credit
 */

- (unsigned)digitValue:(unichar)c {
	
	if ((c>47)&&(c<58)) {
        return (c-48);
	}
	
	return GGCharacterIsNotADigit;
}

- (unsigned long long)unsignedLongLongValue {
	unsigned n = (unsigned )[self length];
	unsigned long long v,a;
	unsigned small_a, j;
	
	v=0;
	for (j=0;j<n;j++) {
		unichar c=[self characterAtIndex:j];
		small_a=[self digitValue:c];
		if (small_a==GGCharacterIsNotADigit) continue;
		a=(unsigned long long)small_a;
		v=(10*v)+a;
	}
	
	return v;
	
}

#pragma mark -
#pragma mark Hashes
// TODO: Add other methods, specifically SHA1

/*
 * Contact info@enormego.com if you're the author and we'll update this comment to reflect credit
 */

- (NSString*)md5 {
	const char* string = [self UTF8String];
	unsigned char result[16];
	CC_MD5(string, (CC_LONG)strlen(string), result);
	NSString* hash = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                      result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
                      result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]];
    
	return [hash lowercaseString];
}

#pragma mark -
#pragma mark Truncation

/*
 * Contact info@enormego.com if you're the author and we'll update this comment to reflect credit
 */

- (NSString*)stringByTruncatingToLength:(int)length {
	return [self stringByTruncatingToLength:length direction:NSTruncateStringPositionEnd];
}

- (NSString*)stringByTruncatingToLength:(int)length direction:(NSTruncateStringPosition)truncateFrom {
	return [self stringByTruncatingToLength:length direction:truncateFrom withEllipsisString:@"..."];
}

- (NSString*)stringByTruncatingToLength:(int)length direction:(NSTruncateStringPosition)truncateFrom withEllipsisString:(NSString*)ellipsis {
	NSMutableString *result = [[NSMutableString alloc] initWithString:self];
	NSString *immutableResult;
	
	if([result length] <= length) {
		return self;
	}
	
	unsigned int charactersEachSide = length / 2;
	
	NSString* first;
	NSString* last;
	
	switch(truncateFrom) {
		case NSTruncateStringPositionStart:
			[result insertString:ellipsis atIndex:[result length] - length + [ellipsis length] ];
			immutableResult  = [[result substringFromIndex:[result length] - length] copy];
			return immutableResult;
		case NSTruncateStringPositionMiddle:
			first = [result substringToIndex:charactersEachSide - [ellipsis length]+1];
			last = [result substringFromIndex:[result length] - charactersEachSide];
			immutableResult = [[[NSArray arrayWithObjects:first, last, NULL] componentsJoinedByString:ellipsis] copy];
			return immutableResult;
		default:
		case NSTruncateStringPositionEnd:
			[result insertString:ellipsis atIndex:length - [ellipsis length]];
			immutableResult  = [[result substringToIndex:length] copy];
			return immutableResult;
	}
}

- (NSString *)stringByDeleteWhitespaceAndWrap{
    NSMutableString *mutableString = [NSMutableString stringWithFormat:@"%@",self];
    
    return [NSString stringWithFormat:@"%@",[mutableString stringByTrimmingCharactersInSet:
                                             [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}



- (NSURL *)url
{
    return [NSURL URLWithString:self];
}

+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}



//时间比较
-(NSString*)formattedExactRelativeDate
{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    NSDate* date = [formatter dateFromString:self];
    
    
    NSTimeInterval time = [date timeIntervalSince1970];
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval diff = now - time;
    
    
    //
    //    	1小时内显示为：XX分钟前
    //    	24小时内显示为：XX小时前
    //    	超过凌晨12点显示为发帖当天日期：如2015-11-11
    
//    //秒
//    if(diff < 10) {
//            return [NSString stringWithFormat:@"刚刚"];
//    } else if(diff < 60) {
//            return [NSString stringWithFormat:@"%d秒前",(int)diff];
//    }
    

    //分钟
    diff = round(diff/60);
    
    if(diff < 15)
    {
        //15分钟内显示为：刚刚
        return [NSString stringWithFormat:@"刚刚"];
    }
    
    //1小时内显示为：XX分钟前
    if(diff < 60)
    {
        return [NSString stringWithFormat:@"%d分钟前",(int)diff];
    }
    
    
    
    //若在同一天，则显示“HH:MM”；
    diff = round(diff/60);
    //24小时内显示为：XX小时前
    
    if(diff < 24)
    {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]];
        NSString * currentDay  = [currentTime substringWithRange:NSMakeRange(5, 5)];
        NSString * timeDays = [self substringWithRange:NSMakeRange(5, 5)];

        if(![currentDay isEqualToString:timeDays])
        {
            //超过凌晨12点显示为发帖当天日期：如2015-11-11
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            return  [dateFormatter stringFromDate:date];
        }
        else
        {
            return [NSString stringWithFormat:@"%d小时前",(int)diff];
            
//            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//            //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
//            [dateFormatter setDateFormat:@"HH:MM"];
//            return  [dateFormatter stringFromDate:date];
        }
    }
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    return  [dateFormatter stringFromDate:date];
    
   
    //若早于当天，则显示：“MM月DD日 HH:MM”
    //    diff = round(diff/24);
    //    if(diff < 7) {
    //        if(diff == 1) {
    //            return @"昨天";
    //        } else
    
    
    /*{
     //return [NSString stringWithFormat:@"%d天前", (int)diff];
     
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     
     [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
     return  [dateFormatter stringFromDate:date];
     }*/
    
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//    NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]];
//    int currentYear  = [[currentTime substringWithRange:NSMakeRange(0, 4)] intValue];;
//    int timeYears = [[self substringWithRange:NSMakeRange(0, 4)] intValue];
//    
//    
//    
//    if(currentYear > timeYears)
//    {
//        //return [NSString stringWithFormat:@"%d天前", (int)diff];
//        
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        
//        [dateFormatter setDateFormat:@"YYYY年MM月dd日 HH:mm"];
//        return  [dateFormatter stringFromDate:date];
//    }
//    else
//    {
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        
//        [dateFormatter setDateFormat:@"MM月dd日 HH:mm"];
//        return  [dateFormatter stringFromDate:date];
//    }
}


+ (NSString *)currentDate{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:@"yyyy-MM-dd"];
    return [dateFormater stringFromDate:now];
}

- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizeWithFont:font maxW:MAXFLOAT];
}

+ (NSString *)formatterToTimeStyle:(int)timeInterval;
{
    int h=((int)timeInterval)/(3600);
    int m=((int)timeInterval)%(3600)/60;
    int s=((int)timeInterval)%(3600)%60;
    
    NSString *timeStr = [NSString stringWithFormat:@"%02d:%02d:%02d",h,m,s];
    return timeStr;
}

@end
